//
//  AUAddressPickerTitleView.swift
//  CreditLoans
//
//  Created by 谢强 on 2017/12/8.
//  Copyright © 2017年 com.ucfpay. All rights reserved.
//

import UIKit

import AwesomeUBaseModule

// MARK:- <定义常量>
/// 文字下边滚动条高度
private let au_kScrollTitleLabelLineHeight: CGFloat = 2
/// titleView下边边线宽度
private let au_kTitleViewBottomLineHeight: CGFloat = 0.5
/// label普通状态文字颜色
private let au_kTitleLabelNormalRGB: (r: CGFloat, g: CGFloat, b: CGFloat) = (43, 44, 46)
/// label选中状态文字颜色
private let au_kTitleLabelSelectedRGB: (r: CGFloat, g: CGFloat, b: CGFloat) = (55, 159, 251)
/// label颜色渐变的变化范围
private let au_colorDelta: (r: CGFloat, g: CGFloat, b: CGFloat) = (au_kTitleLabelSelectedRGB.r - au_kTitleLabelNormalRGB.r, au_kTitleLabelSelectedRGB.g - au_kTitleLabelNormalRGB.g, au_kTitleLabelSelectedRGB.b - au_kTitleLabelNormalRGB.b)

// MARK:- <协议>
@objc protocol AUAddressPickerTitleViewDelegate: class {
    // 协议方法
    func pageTitleView(_ titleView: AUAddressPickerTitleView, clickedIndex index: Int)
}

class AUAddressPickerTitleView: UIView {
    
    fileprivate var adding: Bool = false
    
    public var closeButtonActionCallback: (() -> ())?

    internal weak var delegate: AUAddressPickerTitleViewDelegate?
    
    // MARK:- <属性>
    var address: String {
        var result = ""
        for index in 0..<titles.count - 1 {
            result += "\(titles[index]) "
        }
        result.removeLast()
        return result
    }
    
    fileprivate var titles: [String]
    fileprivate var titleLabels: [UILabel] = [UILabel]()
    fileprivate var currentIndex: Int = 0
    
    fileprivate lazy var scrollView: UIScrollView = {
        let scrollView = UIScrollView()
        scrollView.showsHorizontalScrollIndicator = false;
        scrollView.scrollsToTop = false;
        scrollView.bounces = false;
        return scrollView
    }()
    
    fileprivate lazy var scrollLine: UIView = {
        let scrollLine = UIView()
        scrollLine.backgroundColor = UIColor(au_rgbColor: au_kTitleLabelSelectedRGB.r, g: au_kTitleLabelSelectedRGB.g, b: au_kTitleLabelSelectedRGB.b)
        
        return scrollLine
    }()

    // MARK:- <自定义构造函数 -> 不能放在类扩展中>
    init(frame: CGRect, titles: [String]) {
        
        self.titles = titles
        
        super.init(frame: frame)
        
        // 设置UI界面
        setupUI()
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

// MARK:- <设置UI>
extension AUAddressPickerTitleView {
    
    /// 设置UI界面
    fileprivate func setupUI() {
        
        backgroundColor = UIColor.white
        
        // 1. 添加scrollView
        addSubview(scrollView)
        scrollView.frame = CGRect(x: 0, y: 0, width: frame.size.width, height: frame.size.height)
        
        // 2. 添加Label
        createLabels()
        
        // 3. 添加滚动条和底部边线
        createBottomLineAndScrollLine()
    }
}

// MARK:- <Action>
extension AUAddressPickerTitleView {
    
    /// 给titleView添加标题
    fileprivate func createLabels() {
        
        let titleLabel = UILabel()
        addSubview(titleLabel)
        
        titleLabel.text = "请选择所在地区"
        titleLabel.font = UIFont.au_scaledFont(size: 14)
        titleLabel.textColor = UIColor(au_hexString: "#82848C")
        titleLabel.textAlignment = .center
        titleLabel.sizeToFit()
        titleLabel.center = CGPoint(x: frame.size.width * 0.5, y: 0)
        titleLabel.frame.origin.y = 15 * au_kScreenScale
        
        // 添加关闭按钮
        let closeButton = UIButton()
        addSubview(closeButton)
        
        // 设置关闭按钮
        let bundle = Bundle.init(for: type(of: self))
        if let bundleDict = bundle.infoDictionary {
            let bundleName = bundleDict["CFBundleName"] ?? ""
            if let imagePath = bundle.path(forResource: "addressPicker_close@2x", ofType: "png", inDirectory: "\(bundleName).bundle") {
                if let image = UIImage(contentsOfFile: imagePath) {
                    closeButton.setImage(image, for: .normal)
                }
            }
        }
        closeButton.sizeToFit()
        closeButton.imageEdgeInsets = UIEdgeInsets(
            top: 10 * au_kScreenScale,
            left: 10 * au_kScreenScale,
            bottom: 10 * au_kScreenScale,
            right: 10 * au_kScreenScale)
        closeButton.frame.size = CGSize(width: 35 * au_kScreenScale, height: 35 * au_kScreenScale)
        closeButton.center = titleLabel.center
        closeButton.frame.origin.x = frame.size.width - closeButton.frame.size.width - 5.4 * au_kScreenScale
        closeButton.addTarget(self, action: #selector(closeButtonAction), for: .touchUpInside)
        
        // 创建label
        let label = UILabel()
        label.text = titles.first
        label.font = UIFont.au_scaledFont(size: 15)
        label.textAlignment = NSTextAlignment.center
        label.textColor = UIColor(au_rgbColor: au_kTitleLabelNormalRGB.r, g: au_kTitleLabelNormalRGB.g, b: au_kTitleLabelNormalRGB.b)
        label.tag = 0
        label.sizeToFit()
        
        // 添加到ScrollView中
        scrollView.addSubview(label)
        
        // 存储label
        titleLabels.append(label)
        
        // 给label添加手势
        label.isUserInteractionEnabled = true
        let gesture = UITapGestureRecognizer(target: self, action: #selector(self.titleClicked(_:)))
        label.addGestureRecognizer(gesture)
        
        label.frame.origin.x = 15 * au_kScreenScale
        label.frame.origin.y = frame.height - label.frame.height - 10
    }
    
    /// 添加label
    fileprivate func addLabel(title: String) {
        
        let insertIndex = titleLabels.count == 1 ? 0 : titleLabels.count - 1
        
        // 添加
        titles.insert(title, at: insertIndex)
        
        // 创建label
        let label = UILabel()
        label.text = title
        label.font = UIFont.au_scaledFont(size: 15)
        label.textAlignment = NSTextAlignment.center
        label.textColor = UIColor(au_rgbColor: au_kTitleLabelNormalRGB.r, g: au_kTitleLabelNormalRGB.g, b: au_kTitleLabelNormalRGB.b)
        
        // 添加到ScrollView中
        scrollView.addSubview(label)
        
        // 存储label
        titleLabels.insert(label, at: insertIndex)
        
        // 给label添加手势
        label.isUserInteractionEnabled = true
        let gesture = UITapGestureRecognizer(target: self, action: #selector(self.titleClicked(_:)))
        label.addGestureRecognizer(gesture)
        
        updateTitleView()
    }
    
    /// 创建滚动条和底部边线
    fileprivate func createBottomLineAndScrollLine() {
        
        // 1. 创建滚动条
        guard let label = titleLabels.first else { return }
        label.textColor = UIColor(au_rgbColor: au_kTitleLabelSelectedRGB.r, g: au_kTitleLabelSelectedRGB.g, b: au_kTitleLabelSelectedRGB.b)
        scrollLine.frame = CGRect(x: label.frame.minX, y: frame.size.height - au_kScrollTitleLabelLineHeight, width: label.frame.size.width, height: au_kScrollTitleLabelLineHeight)
        scrollView.addSubview(scrollLine)
        
        // 2. 创建底部边线
        let bottomLineFrame = CGRect(x: 0, y: frame.size.height - au_kTitleViewBottomLineHeight, width: frame.size.width, height: au_kTitleViewBottomLineHeight)
        let bottomLine = UIView(frame: bottomLineFrame)
        bottomLine.backgroundColor = UIColor.lightGray
        addSubview(bottomLine)
    }
    
    fileprivate func updateTitleView() {
        let y = frame.height - titleLabels.last!.frame.height - 10
        let margin: CGFloat = 15 * au_kScreenScale
        var maxX: CGFloat = 0
        
        for (index, titleLabel) in titleLabels.enumerated() {
            titleLabel.tag = index
            titleLabel.sizeToFit()
            
            let x = maxX + margin
            titleLabel.frame.origin.x = x
            titleLabel.frame.origin.y = y
            
            maxX = titleLabel.frame.maxX
        }
        
        scrollView.contentSize = CGSize(width: maxX, height: 0)
        
        if maxX > au_kScreenWidth {
            scrollView.setContentOffset(CGPoint(x: maxX - au_kScreenWidth + margin, y: 0), animated: true)
        }
    }
}

extension AUAddressPickerTitleView {
    @objc fileprivate func closeButtonAction() {
        closeButtonActionCallback?()
    }
}

// MARK:- <事件监听>
extension AUAddressPickerTitleView {
    /// 标题点击
    @objc fileprivate func titleClicked(_ gesture: UIGestureRecognizer) {
        
        // 校验
        guard let label = gesture.view as? UILabel else {return}
        
        // 重复点击同一个title, 直接返回
        if label.tag == currentIndex {return}
        
        // 改变当前点击的label
        label.textColor = UIColor(au_rgbColor: au_kTitleLabelSelectedRGB.r, g: au_kTitleLabelSelectedRGB.g, b: au_kTitleLabelSelectedRGB.b)
        
        // 改变上一个label
        let preLabel = titleLabels[currentIndex]
        preLabel.textColor = UIColor(au_rgbColor: au_kTitleLabelNormalRGB.r, g: au_kTitleLabelNormalRGB.g, b: au_kTitleLabelNormalRGB.b)
        
        // 改变滚动条的位置
        let scrollLineX = label.frame.origin.x
        UIView.animate(withDuration: 0.15, animations: {
            self.scrollLine.frame.origin.x = scrollLineX
            self.scrollLine.frame.size.width = label.frame.width
        })
        
        // 记录当前的index
        currentIndex = label.tag
        
        // 将点击的索引传递给代理
        delegate?.pageTitleView(self, clickedIndex: currentIndex)
    }
}

// MARK:- <公共接口>
extension AUAddressPickerTitleView {
    
    /// 更新标题
    func updateTitle(_ sourceIndex: Int, address: String) {
        if sourceIndex < titles.count - 1 {
            print("更新标题")
            titles[sourceIndex] = address
            titleLabels[sourceIndex].text = address
            
            let count = titles.count - 2 - sourceIndex
            
            if count > 0 {
                // 要截掉的位置
                let tempRange = NSMakeRange(sourceIndex + 1, count)
                let range = Range(tempRange)
                
                for i in (sourceIndex + 1)..<(titles.count - 1) {
                    titleLabels[i].removeFromSuperview()
                }
                
                titles.removeSubrange(range!)
                titleLabels.removeSubrange(range!)
            }
            updateTitleView()
        } else {
            adding = true
            addLabel(title: address)
        }
        
        //        print("完整地址: \(self.address)")
    }
    
    /// 滚动
    internal func setProgress(_ progress: CGFloat, sourceIndex: Int, targetIndex: Int, address: String) {
        
//        if targetIndex > titles.count - 1 {
//            adding = true
//            addLabel(title: address)
//        }
        
        // 取出label
        let sourceLabel = titleLabels[sourceIndex]
        let targetLabel = titleLabels[targetIndex]
        
        // 移动的总距离
        let moveMaxX: CGFloat = targetLabel.frame.origin.x - sourceLabel.frame.origin.x
        
        // 移动的距离
        let moveX: CGFloat = moveMaxX * progress
        
        // 移动滑块
        scrollLine.frame.size.width = targetLabel.frame.width
        scrollLine.frame.origin.x = sourceLabel.frame.origin.x + moveX
        
        // 改变颜色(渐变)
        if !adding {
            sourceLabel.textColor = UIColor(au_rgbColor: au_kTitleLabelSelectedRGB.r - au_colorDelta.r * progress, g: au_kTitleLabelSelectedRGB.g - au_colorDelta.g * progress, b: au_kTitleLabelSelectedRGB.b - au_colorDelta.b * progress)
        }
        targetLabel.textColor = UIColor(au_rgbColor: au_kTitleLabelNormalRGB.r + au_colorDelta.r * progress, g: au_kTitleLabelNormalRGB.g + au_colorDelta.g * progress, b: au_kTitleLabelNormalRGB.b + au_colorDelta.b * progress)
        
        // 记录当前的index
        currentIndex = targetIndex
        
        if progress == 1 {
            adding = false
        }
    }
}
